package com.example.flutter_channel;

import android.util.Log;

import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;


/**
 * 原生和flutter的通道
 *
 * @author : YOULU  ywj
 * date   : 0009 2022/4/9 上午 11:44
 * desc   :
 */
public class MyFlutterPlugin implements MethodChannel.MethodCallHandler, FlutterPlugin {
    public static final String CRM_FLUTTER_CHANNEL_DEFAULT = "CRM_FLUTTER_CHANNEL_DEFAULT";
    private static MyFlutterPlugin instance;
    private MethodChannel channel;

    private MyFlutterPlugin() {
    }

    public static MyFlutterPlugin getInstance() {
        if (instance == null) {
            synchronized (MyFlutterPlugin.class) {
                if (instance == null) {
                    instance = new MyFlutterPlugin();
                }
            }
        }
        return instance;
    }


    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        Log.d("XXX","onMethodCall:" + methodCall.method);
        switch (methodCall.method) {

            case "test": {
                Log.d("XXX","onMethodCall:" + methodCall.method + "," + methodCall.arguments);
                break;
            }
            default: {
                result.notImplemented();
                break;
            }
        }

    }

    @Override
    public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) {
        channel = new MethodChannel(binding.getBinaryMessenger(), MyFlutterPlugin.CRM_FLUTTER_CHANNEL_DEFAULT);
        channel.setMethodCallHandler(this);
    }

    @Override
    public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
        if (channel != null) channel.setMethodCallHandler(null);
    }

    public void callTest() {

        Log.d("XXX","callTest start");
        channel.invokeMethod("test", "哈哈哈哈", new MethodChannel.Result() {
            @Override
            public void success(Object o) {
                Log.d("XXX","callTest success");
            }

            @Override
            public void error(String s, String s1, Object o) {
                Log.d("XXX","callTest error");
            }

            @Override
            public void notImplemented() {
                Log.d("XXX","callTest notImplemented");
            }
        });
    }

}
